<template>
  <div class="fish-species-container">
    <div class="table-operations">
      <a-button type="primary" @click="showAddModal">
        <template #icon><plus-outlined /></template>
        添加鱼类
      </a-button>
      <a-input-search
        v-model:value="searchText"
        placeholder="搜索鱼类名称"
        style="width: 250px; margin-left: 16px"
        @search="onSearch"
      />
    </div>

    <a-table
      :columns="columns"
      :data-source="filteredFishSpecies"
      :loading="loading"
      :pagination="{ pageSize: 10 }"
      row-key="id"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'image'">
          <img
            v-if="record.imageUrl"
            :src="record.imageUrl"
            alt="鱼类图片"
            style="width: 60px; height: 60px; object-fit: cover; border-radius: 4px"
          />
          <span v-else>无图片</span>
        </template>
        <template v-if="column.key === 'conservationStatus'">
          <a-tag :color="getStatusColor(record.conservationStatus)">
            {{ record.conservationStatus }}
          </a-tag>
        </template>
        <template v-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="showEditModal(record)"><EditOutlined /> 编辑</a-button>
            <a-divider type="vertical" />
            <a-popconfirm
              title="确定要删除这条记录吗?"
              ok-text="确定"
              cancel-text="取消"
              @confirm="deleteFishSpecies(record.id)"
            >
              <a-button type="primary" danger><DeleteOutlined /> 删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 添加/编辑鱼类模态框 -->
    <a-modal
      v-model:visible="modalVisible"
      :title="modalTitle"
      @ok="handleModalOk"
      :confirmLoading="confirmLoading"
    >
      <a-form
        :model="formState"
        :rules="rules"
        ref="formRef"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 16 }"
      >
        <a-form-item label="鱼类名称" name="name">
          <a-input v-model:value="formState.name" placeholder="请输入鱼类名称" />
        </a-form-item>
        <a-form-item label="鱼类分类" name="category">
          <a-select v-model:value="formState.category" placeholder="请选择鱼类分类">
            <a-select-option value="淡水鱼">淡水鱼</a-select-option>
            <a-select-option value="海水鱼">海水鱼</a-select-option>
            <a-select-option value="溯河鱼类">溯河鱼类</a-select-option>
            <a-select-option value="软骨鱼">软骨鱼</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="栖息地" name="habitat">
          <a-input v-model:value="formState.habitat" placeholder="请输入栖息地" />
        </a-form-item>
        <a-form-item label="保护状态" name="conservationStatus">
          <a-select v-model:value="formState.conservationStatus" placeholder="请选择保护状态">
            <a-select-option value="无危">无危</a-select-option>
            <a-select-option value="近危">近危</a-select-option>
            <a-select-option value="易危">易危</a-select-option>
            <a-select-option value="濒危">濒危</a-select-option>
            <a-select-option value="极危">极危</a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="图片URL" name="imageUrl">
          <!-- <a-input v-model:value="formState.imageUrl" placeholder="请输入图片URL" /> -->
          <a-upload
            name="image"
            :before-upload="beforeImageUpload"
            :customRequest="handleImageUpload"
            :show-upload-list="false"
          >
          <div v-if="uploadImageUrl">
            <img :src="uploadImageUrl" alt="图片预览" style="width: 80px; height: 80px; object-fit: cover; border-radius: 4px;border: 1px solid #d9d9d9;" />
          </div>
          <a-button v-else>
            <upload-outlined /> 上传图片
          </a-button>
          </a-upload>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { PlusOutlined, UploadOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import { useFishSpeciesStore } from '@/stores/fishSpeciesStore';
import { beforeImageUpload, uploadImage } from '@/api/utils';

const fishSpeciesStore = useFishSpeciesStore();
const loading = computed(() => fishSpeciesStore.loading);
const fishSpecies = computed(() => fishSpeciesStore.fishSpecies);

const searchText = ref('');
const modalVisible = ref(false);
const modalTitle = ref('添加鱼类');
const confirmLoading = ref(false);
const isEdit = ref(false);
const currentId = ref(null);
const formRef = ref(null);
const uploadImageUrl = ref('');

const formState = reactive({
  name: '',
  category: '',
  habitat: '',
  conservationStatus: '无危',
  imageUrl: ''
});

const rules = {
  name: [{ required: true, message: '请输入鱼类名称', trigger: 'blur' }],
  category: [{ required: true, message: '请选择鱼类分类', trigger: 'change' }],
  habitat: [{ required: true, message: '请输入栖息地', trigger: 'blur' }],
  conservationStatus: [{ required: true, message: '请选择保护状态', trigger: 'change' }]
};

const columns = [
  {
    title: '图片',
    key: 'image',
    width: 100
  },
  {
    title: '鱼类名称',
    dataIndex: 'name',
    key: 'name',
    sorter: (a, b) => a.name.localeCompare(b.name)
  },
  {
    title: '分类',
    dataIndex: 'category',
    key: 'category',
    filters: [
      { text: '淡水鱼', value: '淡水鱼' },
      { text: '海水鱼', value: '海水鱼' },
      { text: '溯河鱼类', value: '溯河鱼类' },
      { text: '软骨鱼', value: '软骨鱼' }
    ],
    onFilter: (value, record) => record.category === value
  },
  {
    title: '栖息地',
    dataIndex: 'habitat',
    key: 'habitat'
  },
  {
    title: '保护状态',
    dataIndex: 'conservationStatus',
    key: 'conservationStatus'
  },
  {
    title: '操作',
    key: 'action',
    width: 150
  }
];

const filteredFishSpecies = computed(() => {
  if (!searchText.value) {
    return fishSpecies.value;
  }
  return fishSpecies.value.filter(item => 
    item.name.toLowerCase().includes(searchText.value.toLowerCase())
  );
});

const getStatusColor = (status) => {
  const colorMap = {
    '无危': 'green',
    '近危': 'cyan',
    '易危': 'orange',
    '濒危': 'red',
    '极危': 'purple'
  };
  return colorMap[status] || 'default';
};

const resetForm = () => {
  formState.name = '';
  formState.category = '';
  formState.habitat = '';
  formState.conservationStatus = '';
  formState.imageUrl = '';
  uploadImageUrl.value = '';
  if (formRef.value) {
    formRef.value.resetFields();
  }
};
// 添加鱼类
const showAddModal = () => {
  resetForm();
  isEdit.value = false;
  modalTitle.value = '添加鱼类';
  modalVisible.value = true;
};
// 编辑鱼类
const showEditModal = (record) => {
  isEdit.value = true;
  currentId.value = record.id;
  modalTitle.value = '编辑鱼类';
  
  formState.name = record.name;
  formState.category = record.category;
  formState.habitat = record.habitat;
  formState.conservationStatus = record.conservationStatus;
  formState.imageUrl = record.imageUrl || '';
  
  modalVisible.value = true;
};

// 添加/编辑鱼类
const handleModalOk = () => {
  formRef.value.validate().then(async () => {
    confirmLoading.value = true;
    
    try {
      if (isEdit.value) {
        await fishSpeciesStore.updateFishSpecies(currentId.value, { ...formState });
        message.success('鱼类信息更新成功');
        await fishSpeciesStore.fetchFishSpecies();
      } else {
        await fishSpeciesStore.addFishSpecies({ ...formState });
        message.success('鱼类添加成功');
        await fishSpeciesStore.fetchFishSpecies();
      }
      
      modalVisible.value = false;
      resetForm();
    } catch (error) {
      message.error('操作失败: ' + error.message);
    } finally {
      confirmLoading.value = false;
    }
  }).catch(error => {
    console.log('表单验证失败:', error);
  });
};
// 删除鱼类
const deleteFishSpecies = async (id) => {
  try {
    await fishSpeciesStore.deleteFishSpecies(id);
    message.success('鱼类删除成功');
    await fishSpeciesStore.fetchFishSpecies();
  } catch (error) {
    message.error('删除失败: ' + error.message);
  }
};

const onSearch = () => {
  // 搜索功能已通过计算属性实现
};

onMounted(() => {
  fishSpeciesStore.fetchFishSpecies();
});

// 图片上传
const handleImageUpload = async (file) => {
  const imageUrl = await uploadImage(file);
  formState.imageUrl = imageUrl;
  uploadImageUrl.value = imageUrl;
};
</script>

<style scoped>
.fish-species-container {
  padding: 10px 10px 0;
}

.table-operations {
  margin-bottom: 16px;
  display: flex;
  align-items: center;
}
</style> 